package com.dm.cloud.oauthlib.service.impl;

import cn.hutool.core.util.ArrayUtil;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.dm.cloud.core.config.CommonConstants;
import com.dm.cloud.core.exception.CustomException;
import com.dm.cloud.core.mode.ResultModel;
import com.dm.cloud.core.mode.UserMode;
import com.dm.cloud.core.mode.UserPermission;
import com.dm.cloud.core.service.user.CurrentUserService;
import com.dm.cloud.core.util.RequsetArrtibutesUtil;
import com.dm.cloud.oauthlib.conf.AuthConstants;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.client.HttpClientErrorException;
import org.springframework.web.client.HttpServerErrorException;
import org.springframework.web.client.RestTemplate;

import java.util.List;

@Service
public class OauthCurrentUserServiceImpl implements CurrentUserService {
    @Autowired
    private RestTemplate restTemplate;

    @Override
    public UserMode getCurrentUser() {
        try {
            if(ObjectUtil.isNotEmpty(RequsetArrtibutesUtil.get(CommonConstants.AUTH_USER_DETAIL))){
                System.out.println("直接从request中获取用户数据");
                return RequsetArrtibutesUtil.get(CommonConstants.AUTH_USER_DETAIL);
            }
            System.out.println("通过接口获取用户数据");
            ResultModel res = restTemplate.getForObject("//equip-auth-service/equip-auth-service/oauth2/userinfo", ResultModel.class);
            if(res.getStatus()!=200){
                throw new CustomException(res.getMsg());
            }
            UserMode user = JSONObject.parseObject(JSON.toJSONString(res.getData()),UserMode.class);
            RequsetArrtibutesUtil.put(CommonConstants.AUTH_USER_DETAIL, user);
            return user;
        }catch (HttpClientErrorException e ){
//            System.out.println(e.getMessage());
            ResultModel resultModel = JSONObject.parseObject(e.getResponseBodyAsString(),ResultModel.class);
            throw new CustomException("获取用户信息失败!"+resultModel.getMsg(),resultModel.getStatus(),null);
        }catch (HttpServerErrorException e){
//            System.out.println(e.getMessage());
            ResultModel resultModel = JSONObject.parseObject(e.getResponseBodyAsString(),ResultModel.class);
            throw new CustomException("获取用户信息失败!"+resultModel.getMsg(),resultModel.getStatus(),null);
        }catch (Exception e){
            if(e instanceof CustomException){
                CustomException ce=(CustomException)e;
                throw new CustomException("获取用户信息失败!"+ce.getMsg());
            }
            throw new CustomException("获取用户信息失败!"+e.getMessage());
        }
    }

    @Override
    public String uid() {
        return getCurrentUser().getUid();
    }

    @Override
    public String uname() {
        return getCurrentUser().getUname();
    }

    @Override
    public String chineseName() {
        return getCurrentUser().getChineseName();
    }

    @Override
    public boolean hasPermissions(String[] permissions) {
        UserPermission userPermissions = getCurrentUser().getPermissions();
        for (String permissionStr : permissions) {
            String permission="";
            if(permissionStr.startsWith(AuthConstants.VIEW_PREFIX)){
                permission=permissionStr.substring(AuthConstants.VIEW_PREFIX.length());
                if(userPermissions.hasView(permission)) return true;
            }else if(permissionStr.startsWith(AuthConstants.CODE_PREFIX)){
                permission=permissionStr.substring(AuthConstants.CODE_PREFIX.length());
                if(userPermissions.hasCode(permission)) return true;
            }else if(permissionStr.startsWith(AuthConstants.APP_PREFIX)){
                permission=permissionStr.substring(AuthConstants.APP_PREFIX.length());
                if(userPermissions.hasApp(permission)) return true;
            }
        }
        return false;
    }

    @Override
    public boolean hasRoles(String[] roles) {
        List<String> userRoles = getCurrentUser().getRoles();
        if(userRoles==null || userRoles.isEmpty()){
            return false;
        }
        if(ArrayUtil.containsAny(userRoles.toArray(),roles)){
            return true;
        }
        return false;
    }
}
